<?php

namespace App\Http\Middleware;

use Closure;
use Dingo\Api\Routing\Helpers;

class CheckUserSign
{
    use Helpers;

    /**
     * 验证用户的签名的一致性
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $data = $request->except('sign');
        if(count($data) > 0)
        {

            ksort($data);//键值按照升序进行排列
            $str = '';
            foreach ($data as $k => $v) {
                $str .= $v;
            }
            $str = md5($str . 'laohoulundao');

            if ($str != $request->sign) 
            {
                $url = $request->getRequestUri();
                if(preg_match('/^\/api\/v3/',$url)) //V3版本
                {
                    $data = ['code' => '403', 'message' => '签名错误', 'data' => []];
                }
                else
                {
                    $data = ['code' => 403, 'message' => '签名错误', 'data' => []];
                }
                return $this->response->array($data);
            }

        }
        
        return $next($request);
    }
}
